package com.fy.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 使用 GenericJackson2JsonRedisSerializer 来序列化和反序列化 redis 的 value 值
        ObjectMapper om = new ObjectMapper();
        om.registerModule(new JavaTimeModule()); // 添加Java8时间模块支持
        GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(om);

        // 使用 StringRedisSerializer 来序列化和反序列化 redis 的 key 值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jsonSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jsonSerializer);

        template.afterPropertiesSet();
        return template;
    }

    @Bean(name = "documentRedisTemplate")
    public RedisTemplate<String, byte[]> documentRedisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, byte[]> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());

        template.afterPropertiesSet();
        return template;
    }

    // @Bean
    // public RedissonClient redissonClient(){
    // // 配置类
    // Config config = new Config();
    // // 设置 redis 地址
    // config.useSingleServer().setAddress("redis://192.168.88.150:7002");
    // // 返回
    // return Redisson.create(config);
    // }

    // @Bean
    // public RedissonClient redissonClient2(){
    // // 配置类
    // Config config = new Config();
    // // 设置 redis 地址
    // config.useSingleServer().setAddress("redis://192.168.88.150:7003");
    // // 返回
    // return Redisson.create(config);
    // }
    //
    // @Bean
    // public RedissonClient redissonClient3(){
    // // 配置类
    // Config config = new Config();
    // // 设置 redis 地址
    // config.useSingleServer().setAddress("redis://192.168.88.150:7001");
    // // 返回
    // return Redisson.create(config);
    // }
}
